import os
import argparse
import re
import sys
import threading
import time
import csv

# code_path = 'D:/code/tws_base_1/earphone'
code_path = sys.argv[1]
print(code_path)

# csv_header_list = ['filename', 'line number', 'category', 'confidence', 'error infomation']
csv_header_list = ['filename', 'line number', 'category', 'error infomation']
# print(os.getcwd())
# print(os.listdir('D:/code/tws_base_1'))
file_to_check_list = []
wk = os.walk(code_path)
for root, dirs, files in wk:
    for file in files:
        if re.match(r'[^.].+(\.c|\.h)$', file):
            # print(root + '/' + file)
            file_to_check_list.append(root + '/' + file)
# for i in file_to_check_list:
#     print(i)
# print(file_to_check_list[20])
# for i in file_to_check_list:
#     r = os.popen('python tws_c_codestyle_v0.2.py %s' % i, 'r')
    # print(r.read())


class _CountThread(object):
    def __init__(self):
        self.runing_thread_count = 0

    def add_thread_count(self):
        self.runing_thread_count = self.runing_thread_count + 1

    def del_thread_count(self):
        self.runing_thread_count = self.runing_thread_count - 1


_RESULT_FILE_USE_CSV = True
_USE_MULTI_THREAD = False

thread_list = []
if _USE_MULTI_THREAD:
    count_thread = _CountThread()


if _RESULT_FILE_USE_CSV:
    result_file = './check_result.csv'
    result_file_fd = open(result_file, 'w', encoding='utf8', newline='')
    result_file_csv_writer = csv.writer(result_file_fd)
    result_file_csv_writer.writerow(csv_header_list)


csv_lock = threading.Lock()


def cmd_thread(file_path):
    r = os.popen('python3 tws_lint_v0.3.py args %s' % file_to_check_list[file_path], 'r')
    # print(r.read())
    lines = r.readlines()
    csv_data = []
    for line in lines:
        if line.strip():
            line = line.strip('\n')
            if _RESULT_FILE_USE_CSV:
                csv_data.append(re.split(r'\]    \[', line, 5))  # modify: re.split(r'\]    \[', line, 5)-->re.split(r'   ', line, 5)
                # temp = re.split(r':', csv_data[0])
                # csv_data[0] = temp[0]
                # csv_data.insert(1, temp[1])
                # csv_lock.acquire()
                # result_file_csv_writer.writerow(csv_data)
                # csv_lock.release()
            else:
                print(line)
    if csv_data and _RESULT_FILE_USE_CSV:
        csv_lock.acquire()
        result_file_csv_writer.writerows(csv_data)
        csv_lock.release()
    if _USE_MULTI_THREAD:
        count_thread.del_thread_count()


time_cost = time.perf_counter()


for i in range(0, len(file_to_check_list)):
    if _USE_MULTI_THREAD:
        while count_thread.runing_thread_count > 8:
            time.sleep(0.3)
        t = threading.Thread(name='t%s' % i, target=cmd_thread, args=(i,))
        t.start()
        count_thread.add_thread_count()
    else:
        cmd_thread(i)


print(f'coast:{time.perf_counter() - time_cost:.8f}s')
